package au.edu.utas.yu_qiao_group.luckyman.ui.raffleshome;

import android.app.Dialog;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import au.edu.utas.yu_qiao_group.luckyman.MainActivity;
import au.edu.utas.yu_qiao_group.luckyman.R;
import au.edu.utas.yu_qiao_group.luckyman.databinding.TicketSellingDialogBinding;
import au.edu.utas.yu_qiao_group.luckyman.db.raffles.RaffleDTO;
import au.edu.utas.yu_qiao_group.luckyman.service.TicketService;
import au.edu.utas.yu_qiao_group.luckyman.utils.FormatUtils;
import au.edu.utas.yu_qiao_group.luckyman.utils.ValidationMessage;

public class TicketSellingDialog extends Dialog {
  RaffleDTO mRaffle;
  private TextView mCancelBtn, mConfirmBtn, mTotalPriceView;
  private Button mIncreaseBtn, mDecreaseBtn;
  private EditText mTicketNumInput;
  private AutoCompleteTextView mCustomerPhoneInput;
  private onSubmitListener mOnSubmit;
  public interface onSubmitListener {
    public void onSubmit();
  }

  public TicketSellingDialog(Context context, MainActivity activity, int width, int height, TicketSellingDialogBinding binding, int style) {

    super(context, style);

    mOnSubmit = null;

    View layout = binding.getRoot();

    mRaffle = binding.getRaffle();

    setContentView(layout);

    Window window = getWindow();

    WindowManager.LayoutParams params = window.getAttributes();

    params.gravity = Gravity.CENTER;

    window.setAttributes(params);
    mCancelBtn = layout.findViewById(R.id.dialog_cancel_btn);
    mConfirmBtn = layout.findViewById(R.id.dialog_confirm_button);
    mIncreaseBtn = layout.findViewById(R.id.dialog_increase_btn);
    mDecreaseBtn = layout.findViewById(R.id.dialog_decrease_btn);
    mTicketNumInput = layout.findViewById(R.id.ticket_num_input);
    mTotalPriceView = layout.findViewById(R.id.dialog_total_price);
    // set autocomplete
    mCustomerPhoneInput = layout.findViewById(R.id.dialog_customer_phone_input);
    List<String> customerList = TicketService.getCustomerRecord(activity.mDb);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_activated_1, customerList);
    mCustomerPhoneInput.setAdapter(adapter);
    mCustomerPhoneInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {

      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
          mCustomerPhoneInput.showDropDown();
        }
      }
    });
    mTicketNumInput.setText("0");

    mTicketNumInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus == false) {
          updateTotalPrice();
        }
      }
    });
    mIncreaseBtn.setOnClickListener(new Button.OnClickListener() {
      @Override
      public void onClick(View v) {
        Editable current = mTicketNumInput.getText();
        int currentNum = Integer.parseInt(current.toString());
        if (currentNum < mRaffle.getMSingleLimit()) {
          mTicketNumInput.setText("" + (currentNum + 1));
          updateTotalPrice();
        }
      }
    });

    mDecreaseBtn.setOnClickListener(new Button.OnClickListener() {
      @Override
      public void onClick(View v) {
        Editable current = mTicketNumInput.getText();
        int currentNum = Integer.parseInt(current.toString());
        if (currentNum > 0) {
          mTicketNumInput.setText("" + (currentNum - 1));
          updateTotalPrice();
        }
      }
    });

    mCancelBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        cancel();
      }
    });

    mConfirmBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        int tn = Integer.parseInt(mTicketNumInput.getText().toString());
        String phone = mCustomerPhoneInput.getText().toString();
        ValidationMessage r = validate(tn, phone);
        if (r.getMIsValid() == ValidationMessage.INVALID_KEY) {
          Toast.makeText(context, r.getMInvalidMessage(), Toast.LENGTH_SHORT).show();
          return;
        }
        boolean result = false;
        try{
          result = TicketService.batchInsertTicket(activity.mDb, mRaffle, phone, tn);
        } catch (Exception e) {
          Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        if (result == true) {
          if (mOnSubmit != null) {
            mOnSubmit.onSubmit();
          }
          dismiss();
        }
      }
    });
  }

  private void updateTotalPrice() {
    long price = Long.parseLong(mTicketNumInput.getText().toString()) * mRaffle.getMUnitPrice();
    mTotalPriceView.setText(FormatUtils.formatCurrency(price));
  }

  public void setOnSubmit(onSubmitListener listener) {
    mOnSubmit = listener;
  }
  protected ValidationMessage validate(int tn, String phone) {
    if (tn <= 0 || tn > mRaffle.getMSingleLimit()) {
      return new ValidationMessage(ValidationMessage.INVALID_KEY, "Ticket count should be within single limitation");
    }

    if (TextUtils.isEmpty(phone) || phone.length() != 10) {
      return new ValidationMessage(ValidationMessage.INVALID_KEY, "Customer phone length should be 10");
    }
    return new ValidationMessage(ValidationMessage.VALID_KEY, "");
  }
}
